import React, {useRef, useEffect, useState, useLayoutEffect} from 'react';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import Overlay from 'ol/Overlay';
import { fromLonLat } from 'ol/proj';
import { Cluster } from 'ol/source';
import VectorSource from 'ol/source/Vector';
import { Feature} from 'ol';
import {add,toStringHDMS} from 'ol/coordinate'
import { Icon, Style } from 'ol/style';
import {Point} from "ol/geom";
import VectorLayer from "ol/layer/Vector";
import * as ReactDom from "react-dom/client";
import {createPortal} from 'react-dom';
import styles from "./styles/Map.module.css"
import {ImageStatic} from "ol/source";
import {Image as ImageLayer} from "ol/layer";

const OverlayPool = [];


function CustomMaker(){
    return (<div className={styles.textMarker}>11111</div>)
}

const imageSource=new ImageStatic({
    url: '/m3.png',
    projection: 'EPSG:3857',
    imageExtent: [1267/5, 826/5, 1267/1.5, 826/1.5],
    zoom:1

});
imageSource.on('error', function(event) {
    console.error('Error loading image:', event);
});
const imageLayer = new ImageLayer({
    source: imageSource
});

function MapComponent({data}) {
    const mapRef = useRef(null);
    const [markers, setMarkers] = useState([]);

    useEffect(() => {
        // 创建地图
        const map = new Map({
            target: 'map',
            layers: [
                // new TileLayer({
                //     source: new OSM()
                // }),
                imageLayer,
                // 创建Vector
                new VectorLayer({
                    source: new VectorSource({
                        features: markers.map((marker) =>
                            new Feature({
                                geometry: new Point([marker.lng, marker.lat]),
                            })
                        ),
                    }),
                    // Add custom marker style (optional)
                    // style: iconStyle, // uncomment if you want custom style
                }),

            ],
            view: new View({
                center: [0, 0],
                zoom:1,
                extent: [0, 0, 1267, 826]
            })
        });
        mapRef.current = map;

        map.on('singleclick', function(evt) {
            const coordinate = evt.coordinate;
            const hdms = toStringHDMS(coordinate);
            console.log('坐标：', hdms,coordinate);
        });

        // 创建 Marker
        const newMarkers = [];
        // 假设您有一个数据数组，每个元素包含经纬度和 HTML 内容

        data.forEach(item => {
            newMarkers.push({
                position: [item.lng, item.lat],
                content: item.content
            });
        });
        setMarkers(newMarkers);
        return () => {
            map.setTarget(null); // 清除地图
        };
    }, []);

    // Marker 组件
    function Marker({ position, content,className }) {
        const overlayRef = useRef(null);
        const portalContainerRef = useRef(null);

        useLayoutEffect(() => {
            if (!overlayRef.current) {
                const overlay = OverlayPool.pop() || new Overlay({
                    element: document.createElement('div'),
                    className:className
                });
                overlay.setPosition(position);
                // overlay.getElement().innerHTML=content;
                overlayRef.current = overlay;
                mapRef.current.addOverlay(overlay);
                console.log(portalContainerRef.current,"=========================>");
                portalContainerRef.current = ReactDom.createRoot(overlay.getElement());
            } else {
                overlayRef.current.setPosition(position);
                // overlayRef.current.getElement().innerHTML = content;
            }
            portalContainerRef.current.render(content);
            return () => {
                OverlayPool.push(overlayRef.current);
                mapRef.current.removeOverlay(overlayRef.current);
                overlayRef.current = null;
                portalContainerRef.current=null;
            };
        }, [position, content, mapRef]);
        return null;
        // return createPortal(
        //     <div ref={portalContainerRef} />, // 这里实际上什么都不渲染，只是为了让 useRef 有效
        //     document.body // 可以将 portal 挂载到任意 DOM 节点
        // );
    }

    // // 自定义 Marker 样式
    // const iconStyle = new Style({
    //     image: new Icon({
    //         src: 'your-icon.png',
    //         scale: 0.5
    //     })
    // });

    return (
        <div id="map" style={{ width:"1280px", height: '960px' }}>
            {markers.map((marker, index) => (
                <Marker key={index} position={marker.position} content={<CustomMaker></CustomMaker>} className={"map-marker"} />
            ))}
        </div>
    );
}
export default MapComponent